<template>
	<div class="home-screen-module9" ref="content">
		<div class="chart-box" ref="chart"></div>
	</div>
</template>

<script setup>
import { ref, onBeforeUnmount, toRefs, getCurrentInstance, onMounted } from 'vue';
import * as echarts from 'echarts';
import { eleResize } from '@/assets/js/utils'

const instance = getCurrentInstance()
const props = defineProps({
	dataSource:{
		type:Array,
		default:function(){
			return []
		}
	}
})
const {dataSource} = toRefs(props)

let $frame = null;
let $dom = null;
let myChart = null;
const defaultOption = {
	tooltip: {
		trigger: 'item',
		formatter: "{a} <br/>{b}: {c} ({d}%)"
	},
	legend: {
		show: true,
		top:'3%',
		right:'1.5%',
		textStyle:{
			color:'#fff'
		},
		orient:'vertical'
	},
	grid:{
		left:'left'
	},
	series: [
		{
			name: '不良统计',
			type: 'pie',
			radius: ['70%', '78%'],
			itemStyle: {
				borderRadius: 4,
				borderColor: '#fff',
				borderWidth: 2
			},
			label:{
				show:false
			},
			center:['38%','50%'],
			data: []
		}
	]
}

const createChart = function(){
	if (!$dom) {
		$dom = instance.refs.chart;
		myChart = echarts.init($dom)
	}
}

const drawChart = function(){
	if (dataSource.value.length<=0) return false;
	let opt = JSON.parse(JSON.stringify(defaultOption))
	for (let i=0;i<dataSource.value.length;i++) {
		let obj = {
			value:dataSource.value[i].qualityNumber,
			name:dataSource.value[i].qualityName,
			itemStyle:{
				color:dataSource.value[i].qualityColour
			}
		}
		opt.series[0].data.push(obj)
	}
	destoryChart()
	createChart()
	myChart.setOption(opt)
}

const destoryChart = function(){
	try{
		myChart.dispose();
		$dom.innerHTML = '';
		myChart = null;
		$dom = null;
	}catch(e){
		//TODO handle the exception
	}
}

/* 创建div宽高变化监听器 */
const createEleResize = function(){
	$frame = instance.refs.content;
	eleResize.on($frame, drawChart);
}

/* div宽高变化事件移除 */
const destroyEleResize=function(){
	try{
		eleResize.off($frame, drawChart);
		$frame = null
	}catch(e){
		//TODO handle the exception
	}
}

onMounted(()=>{
	createEleResize()
})

onBeforeUnmount(()=>{
	destroyEleResize()
	destoryChart()
})

defineExpose({drawChart})
</script>

<style lang="scss" scoped>
.home-screen-module9{
	height: 100%;
	.chart-box{
		height: 100%;
	}
}
</style>